'''
支持向量机
'''
from sklearn import svm
import scipy.io as scio
import datetime
import numpy as np
from sklearn import metrics

# 读取mat文件
def readMat(matPath):
    return scio.loadmat(matPath)

# 加载数据集
matPath='dataSet20180403-K3.mat'
dataSet=readMat(matPath)
print('数据集读取完成')

# 读取数据集
test=np.array(dataSet['test'])
testX=np.array(dataSet['testX'])
testY=np.array(dataSet['testY']).T[0]
train=np.array(dataSet['train'])
trainX=np.array(dataSet['trainX'])
trainY=np.array(dataSet['trainY']).T[0]
print('数据集读取完成')

# SVM准备
paraResult=[]
kernelSVC='rbf'
gammaSVC=[0.000001,0.00001,0.0001,0.001,0.01,0.1,1,10,100]
cSVC=[0.001,0.01,0.1,1,10,100,1000]
for c in cSVC:
    for g in gammaSVC:
        startTime = datetime.datetime.now()
        print('kernelSVC:' + kernelSVC+',gammaSVC:'+str(g)+',penalty:' + str(c))
        clf = svm.SVC(kernel=kernelSVC, C=c,gamma=g)
        clf.fit(trainX, trainY)
        score = clf.score(trainX, trainY)
        print('训练精度：' + str(score))
        score = clf.score(testX, testY)
        print('测试精度：' + str(score))
        predictY = clf.predict(testX)
        print('召回率：' + str(metrics.recall_score(testY, predictY)))
        confusion_matrix = metrics.confusion_matrix(testY, predictY)
        print("混淆矩阵：\n %s" % confusion_matrix)
        TP = confusion_matrix[1][1]
        TN = confusion_matrix[0][0]
        FN = confusion_matrix[1][0]
        FP = confusion_matrix[0][1]
        accuracy = (TP + TN) / (TP + TN + FN + FP)
        Specitivity = TN / (TN + FP)
        Sensitivity = TP / (TP + FN)
        print("准确度： %s" % accuracy)
        print("特异度： %s" % Specitivity)
        print("敏感度： %s" % Sensitivity)

        paraResultItem = {}
        paraResultItem['kernelSVC'] = kernelSVC
        paraResultItem['gammaSVC'] = g
        paraResultItem['penalty'] = c
        paraResultItem['score'] = score
        paraResult.append(paraResultItem)
        endTime = datetime.datetime.now()
        print(endTime - startTime)
print('rbf结束')